# ---------------------------------
# Title: 
#       Main Graphs in "Preparing for an Aging Africa: 
#       Data-Driven Priorities for Economic Research and Policy"
# Description: 
#             This script generates visualizations to explore demographic
#             trends in Africa, focusing on population growth, dependency
#             ratios, and aging trends across various countries. Key insights
#             on the population aged 60 and above are highlighted, along with
#             other relevant demographic variables to support policy analysis
#             and decision-making.
# Output: 
#       Colored PNG images for use in presentations, reports, and academic publications.
# Date:
#       December 17, 2024
# ---------------------------------

# ---------------------------------
# Figure 1: Panel B: Over-60 Population (Millions)
# ---------------------------------

# Population of individuals aged 60 and above across various countries over time.
newggslopegraph(
  dataframe = proj_pop,          # Data source containing the population data
  Times = measurement,           # Time variable (e.g., years)
  Measurement = value,           # The value to be plotted (e.g., population size in millions)
  Grouping = countryregion,      # Grouping by country to create separate lines for each country
  Title = "",                    # Title for the plot (none for this plot)
  SubTitle = "",                 # Subtitle for the plot (none for this plot)
  Caption = NULL,                # Caption for the plot (none for this plot)
  DataTextSize = 4,              # Size of text for data labels
  YTextSize = 4,                 # Size of text for Y-axis labels
  XTextSize = 15,                # Size of text for X-axis labels
  TitleTextSize = 10,            # Size of text for the title
  SubTitleTextSize = 2,          # Size of text for subtitle
  LineThickness = 1,             # Line thickness for the slope graph
  LineColor = rep(c_green, nrow(proj_pop)),  # Line color, applied to each country
  WiderLabels = TRUE,            # Whether to use wider labels for better readability
  ThemeChoice = "minimal"        # Use a minimal theme for the plot
)

# Save the plot as a PNG file with specified dimensions and resolution
ggsave(
  filename = "pop_grow.png",     # File name for the saved image
  width = 5,                     # Plot width in inches
  height = 6,                    # Plot height in inches
  dpi = 100,                     # Resolution of the saved image (dots per inch)
  device = "png",                # Format of the saved image (PNG)
  path = path_figs,              # Save directory
  bg = "white"                    # Transparent background
)

# ---------------------------------
# Figure 2: Projected Population Growth and Dependency Ratios
# ---------------------------------

# Panels A & B:
# --------------

# Plot 2a: General Population (Total)
fig2a <- ggplot(
  totpop, aes(condition, measurement, fill = countryregion, label = countryregion)
) +
  geom_area(type = "ridge", bw = 1) +
  geom_text(
    data = stacked_labels, 
    aes(condition, measurement, label = labels), 
    hjust = 0, vjust = 0.5, color = stacked_labels$color, size = 8
  ) +
  add_annotation(2100.2, cent(totpop, 1), "· 4.6B", "#818589", size_share) +
  add_annotation(2100.2, cent(totpop, 2), "· 0.8B", pal[3], size_share) +
  add_annotation(2100.2, cent(totpop, 3), "· 1.5B", pal[2], size_share) +
  add_annotation(2100.2, cent(totpop, 4), "· 3.4B", pal[1], size_share) +
  add_segment(2050, end_val(totpop, 2050)) +
  geom_point(aes(x = 2050, y = end_val(totpop, 2050)), color = "black") +
  add_annotation(2050, end_val(totpop, 2050) + 400000, "9.7B", "black", sz_tot) +
  add_segment(2020, end_val(totpop, 2020)) +
  geom_point(aes(x = 2020, y = end_val(totpop, 2020)), color = "black") +
  add_annotation(2020, end_val(totpop, 2020) + 400000, "7.8B", "black", sz_tot) +
  add_segment(1990, end_val(totpop, 1990)) +
  geom_point(aes(x = 1990, y = end_val(totpop, 1990)), color = "black") +
  add_annotation(1990, end_val(totpop, 1990) + 400000, "5.3B", "black", sz_tot) +
  add_segment(2100, end_val(totpop, 2100)) +
  geom_point(aes(x = 2100, y = end_val(totpop, 2100)), color = "black") +
  add_annotation(2100, end_val(totpop, 2100) + 400000, "10.3B", "black", sz_tot) +
  scale_fill_manual(values = pal) +
  coord_cartesian(clip = "off") +
  theme_minimal() +
  labs(title = '**General Population<br><br><br>A1. Total Population**', y = "", x = "") +
  theme(
    panel.grid = element_blank(),
    axis.text.y = element_blank(),
    plot.title = element_markdown(size = 20, color = blue_colo, hjust = 0.5),
    axis.text.x = element_text(size = 20, margin = margin(5, 0, 0, 0)),
    plot.margin = margin(-1, 20, 0, 2),
    legend.position = "none"
  ) +
  scale_x_continuous(breaks = breaks_numer, labels = breaks_text)

# Plot 2b: Over 60 Population (Total)
fig2b <- ggplot(over60, aes(condition, measurement, fill = countryregion, label = countryregion)) +
  geom_area(type = "ridge", bw = 1) +
  add_annotation(2100.2, cent(over60, 1), "· 1,526M", "#818589", size_share) +
  add_annotation(2100.2, cent(over60, 2), "· 362M", pal[3], size_share) +
  add_annotation(2100.2, cent(over60, 3), "· 552M", pal[2], size_share) +
  add_annotation(2100.2, cent(over60, 4), "· 644M", pal[1], size_share) +
  add_segment(1990, end_val(over60, 1990)) +
  geom_point(aes(x = 1990, y = end_val(over60, 1990)), color = "black") +
  add_annotation(1990, end_val(over60, 1990) + 120000, "483M", "black", sz_tot) +
  add_segment(2020, end_val(over60, 2020)) +
  geom_point(aes(x = 2020, y = end_val(over60, 2020)), color = "black") +
  add_annotation(2020, end_val(over60, 2020) + 120000, "1,061M", "black", sz_tot) +
  add_segment(2050, end_val(over60, 2050)) +
  geom_point(aes(x = 2050, y = end_val(over60, 2050)), color = "black") +
  add_annotation(2050, end_val(over60, 2050) + 120000, "2,132M", "black", sz_tot) +
  add_segment(2100, end_val(over60, 2100)) +
  geom_point(aes(x = 2100, y = end_val(over60, 2100)), color = "black") +
  add_annotation(2100, end_val(over60, 2100) + 120000, "3,084M", "black", sz_tot) +
  scale_fill_manual(values = pal) +
  coord_cartesian(clip = "off") +
  theme_minimal() +
  labs(title = '**Over 60 Population<br><br><br>B1. Total Population**', y = "", x = "") +
  theme(
    panel.grid = element_blank(),
    axis.text.y = element_blank(),
    plot.title = element_markdown(size = 20, color = blue_colo, hjust = 0.5),
    axis.text.x = element_text(size = 20, margin = margin(5, 0, 0, 0)),
    plot.margin = unit(c(0, 0.75, 0, 0), "inches"),
    legend.position = "none"
  ) +
  scale_x_continuous(breaks = breaks_numer, labels = breaks_text)

# Panels C & D:
# --------------

# Plot 2c: General Population (Growth)
fig2c <- base_plot_comp(
  fig2c_data, '**<br><br><br>A2. Growth**',
  y_labels = c(0, 500000, 1000000, 1500000, 2000000, 2500000, 3000000, 3500000),
  y_limits = c(0, 3500000)
) %>%
  enrich_with_labels(
    fig2c_labels, curvature = -0.3, show_countryregion_labels = TRUE
  ) %>%
  add_curves()

# Plot 2d: Over 60 Population (Growth)
fig2d <- base_plot_comp(
  fig2d_data, '**<br><br><br>B2. Growth**',
  y_labels = c(0, 200000, 400000, 600000, 800000),
  y_limits = c(0, 800000)
) %>%
  enrich_with_labels(
    fig2d_labels, curvature = -0.1, show_countryregion_labels = FALSE
  ) %>%
  
  add_curves()

# Panels E & F:
# --------------

# Generate the dependency ratio plot for the general population
fig2e <- create_dependency_ratio_plot(
  data = dep_rat_ov60,                             # Input data for general population
  title = "**<br><br><br>A3.- Dependency Ratio**", 
  line_sizes = c(0.9, 0.9, 1.6),                   # Line thicknesses
  color_scheme = colors_scheme,                    # Color scheme for the plot
  breaks_numer = breaks_numer,                     # X-axis numeric breaks
  breaks_text = breaks_text,                       # X-axis text labels
  include_country_labels = TRUE                    # Include country labels
)

# Generate the dependency ratio plot for the over-60 population
fig2f <- create_dependency_ratio_plot(
  data = old_age_rat_ov60,                         # Input data for over-60 population
  title = "**<br><br><br>B3.- Dependency Ratio**",
  line_sizes = c(0.9, 0.9, 1.6),                   # Line thicknesses
  y_labels = c("0", "-", "0.5", "-", "1", "1.25", "1.50"), # Custom y-axis labels
  color_scheme = colors_scheme,                    # Color scheme for the plot
  breaks_numer = breaks_numer,                     # X-axis numeric breaks
  breaks_text = breaks_text,                       # X-axis text labels
  include_country_labels = FALSE                   # Exclude country labels
)

# Combine both plots into a single figure with a custom "Year" tag
com_coun <- wrap_elements(
  plot_grid(fig2a | fig2b, fig2c | fig2d, fig2e + fig2f, ncol = 1)
) + 
  labs(tag = "**Year**") +                  
  theme(
    plot.tag = element_markdown(size = 20, color = blue_colo),
    plot.tag.position = "bottom"                  
  )

# Save the combined plot as a high-resolution PNG file
ggsave(
  filename = "com_coun.png",      # Output filename
  plot = com_coun,         # Combined plot to save
  width = 18,                     # Plot width (inches)
  height = 24,                    # Plot height (inches)
  dpi = 100,                      # Resolution: 100 dpi
  device = "png",                 # Save as PNG format
  path = path_figs,               # Save directory
  bg = "white"                    # Transparent background
)

# ---------------------------------
# Figure 3: Employment, Health, & Living Arrangements 
# over the Life Course: Aggregate
# ---------------------------------

# Create a dataframe for text labels
meas_labs_text <- data.frame(
  condition = measures,            # Conditions for which labels are applied
  country = c(avg_text, "", "", ""),
  label = c(avg_text, "", "", "")
)

# Call the function with customizable text position
country_average(
  data = count_avera(ssa_wgt, measures),
  vars = measures,
  labels = measures_labs_agg,
  forma_theme = theme_top_count(
    size_text=18,
    size_title=20,
    size_legend=20,
    color=blue_colo
  ),
  f_labels_data = meas_labs_text,
  label_conditions = label_measu,  # Pass label conditions
  geom_text_x = "40",  # Custom x position for the text
  geom_text_y = 0.30    # Custom y position for the text
) %>% 
  # Add formatted axes
  forma_axes(
    bre_age, 
    lab_age, 
    break_propo, 
    label_propo, 
    limi_propo
  )

# Save the plot as a high-resolution PNG
ggsave(
  filename = "out_cou_wgt.png",     # Output filename
  width = 18,                       # Plot width (inches)
  height = 16.5,                    # Plot height (inches)
  dpi = 100,                        # Resolution: 100 dpi
  device = "png",                   # Output format
  path = path_figs,                 # Save directory
  bg = "white"                      # Transparent background
)

# ---------------------------------
# Figure 4: Employment, Health, & Living Arrangements 
# over the Life Course: by Gender
# ---------------------------------
# Generate the gender-disaggregated plot
country_gender(
  count_gender(gen_wgt, measures),                 # Input data for gender-disaggregated outcomes
  measures,                    # Variables to visualize
  measures_labs_agg,           # Labels for measures
  theme_top_count(
    size_text=18,
    size_title=20,
    size_legend=20,
    color=blue_colo
  ),
  vars_with_text = label_measu
) %>%
  # Add formatted axes
  forma_axes(
    bre_age, 
    lab_age, 
    break_propo, 
    label_propo, 
    limi_propo
  )

# Save the plot as a high-resolution PNG
ggsave(
  filename = "out_gen_wgt.png", # Output filename
  width = 18,                   # Plot width (inches)
  height = 18,                  # Plot height (inches)
  dpi = 100,                    # Resolution: 100 dpi
  device = "png",               # Output format
  path = path_figs,             # Save directory
  bg = "white"                  # Transparent background
)

# ---------------------------------
# Figure 5: Functional Limitations over the Life Course
# ---------------------------------

# Prepare labels data
limi_labs_text <- data.frame(
  condition = limitations,
  country = avg_text,
  label = avg_text
)

# Generate the aggregate limitations plot
country_average(
  data = count_avera(ssa_wgt, limitations) ,     # Input data
  vars = limitations,                            # Variables to visualize
  labels = limitations_labs,                     # Labels for the variables
  forma_theme = theme_top_count(                 # Custom theme settings
    size_text = 18,                              # Text size
    size_title = 20,                             # Title size
    size_legend = 20,                            # Legend size
    color = blue_colo                            # Color scheme
  ),
  f_labels_data = limi_labs_text,                # Data for custom labels
  label_conditions = label_limit,                # Specify conditions for labels
  geom_text_x = "40",                            # X position for text labels
  geom_text_y = 0.15                             # Y position for text labels
) %>%
  # Format axes with custom breaks and labels
  forma_axes(
    bre_age, 
    lab_age, 
    break_propo, 
    label_propo, 
    limi_propo
  )
# Save the resulting plot as a high-resolution PNG with a transparent background
ggsave(
  filename = "lim_cou_wgt.png",   # Output filename
  width = 18,                     # Plot width (inches)
  height = 10.5,                  # Plot height (inches)
  dpi = 100,                      # Resolution: 100 dpi
  path = path_figs,               # Save directory
  bg = "white"                    # Transparent background
)

# ---------------------------------
# Figure 6: Functional Limitations 
# Over the Life Course By Gender
# ---------------------------------

# Generate the gender-specific limitations plot
country_gender(
  count_gender(gen_wgt, limitations),                    # Input data (gender-weighted)
  limitations,                    # Variables to visualize
  limitations_labs,               # Labels for the variables
  theme_top_count(                # Custom theme settings
    size_text = 18,               # Size of the text
    size_title = 20,              # Size of the title
    size_legend = 20,             # Size of the legend
    color = blue_colo             # Color scheme
  ),
  vars_with_text = label_limit
) %>%
  # Format axes with custom breaks and labels
  forma_axes(
    bre_age, 
    lab_age, 
    break_propo, 
    label_propo, 
    limi_propo
  )

# Save the resulting plot as a high-resolution PNG with a transparent background
ggsave(
  filename = "lim_gen_wgt.png",   # Output filename
  width = 18,                     # Plot width (inches)
  height = 12,                    # Plot height (inches)
  dpi = 100,                      # Resolution: 100 dpi
  device = "png",                 # Output format
  path = path_figs,               # Save directory
  bg = "white"                    # White background
)

# ---------------------------------
# Figure 7: Social Protection Across
# Selected Sub-Saharan African Countries
# ---------------------------------

# Generate the social protection plot
indi_coun_regi(
  vars=indicators,
  labs=indicato_labeller
)

# Save the plot as a high-resolution PNG with a transparent background
ggsave(
  filename = "environ.png",        # Output filename
  width = 15,                      # Plot width (inches)
  height = 7.5,                    # Plot height (inches)
  dpi = 100,                       # Resolution: 100 dpi
  device = "png",                  # Output format
  path = path_figs,                # Save directory
  bg = "white"                     # White background
)

# ---------------------------------
# Figure 8: Health Spending and Health 
# Care Capacity Across Selected Sub-Saharan African Countries
# ---------------------------------

# Generate the health spending and capacity plot
indi_coun_regi(
  vars = var_hea,                  # Health-related variables
  labs = labeller_health           # Custom labeller for variable descriptions
)

# Save the plot as a high-resolution PNG with a transparent background
ggsave(
  filename = "hea_care.png",        # Output filename
  width = 18,                      # Plot width (inches)
  height = 7.5,                    # Plot height (inches)
  dpi = 100,                       # Resolution: 100 dpi
  device = "png",                  # Output format
  path = path_figs,                # Save directory
  bg = "white"                     # White background
)
